package com.lh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.utils.Answer;
import com.lh.utils.LogUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lh.mapper.AreaInfoMapper;
import com.lh.entity.table.AreaInfo;
import com.lh.service.AreaService;

@Service
public class AreaServiceImpl implements AreaService {

    private LogUtil LOG = new LogUtil(AreaService.class);

    @Resource
    private AreaInfoMapper areaInfoMapper;


    @Override
    public Answer<Object> addAreaInfo(AreaInfo areaInfo) {
        try {
            String areaCode = areaInfo.getAreaCode();
            if (StrUtil.isBlank(areaCode)) {
                return Answer.build(HttpServletResponse.SC_OK, "", "areaCode不能为空");
            }
            String areaName = areaInfo.getAreaName();
            if (StrUtil.isBlank(areaName)) {
                return Answer.build(HttpServletResponse.SC_OK, "", "areaName不能为空");
            }
            String parentCode = areaInfo.getParentCode();
            if (StrUtil.isBlank(parentCode)) {
                return Answer.build(HttpServletResponse.SC_OK, "", "parentCode不能为空");
            }
            String parentName = areaInfo.getParentName();
            if (StrUtil.isBlank(parentName)) {
                return Answer.build(HttpServletResponse.SC_OK, "", "parentName不能为空");
            }
            areaInfoMapper.insert(areaInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求addAreaInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> updateAreaInfo(AreaInfo areaInfo) {
        try {
            Integer id = areaInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_OK, "", "id不能为空");
            }
            areaInfoMapper.updateById(areaInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求updateAreaInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> deleteAreaInfo(AreaInfo areaInfo) {
        try {
            Integer id = areaInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_OK, "", "id不能为空");

            }
            areaInfoMapper.deleteById(id);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求deleteAreaInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> getAreaInfo(AreaInfo areaInfo) {
        try {
            Integer id = areaInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_OK, "", "id不能为空");
            }
            return Answer.ok(areaInfoMapper.selectById(id));
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getAreaInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> getAreaChildInfo(AreaInfo areaInfo) {
        try {
            String areaCode = areaInfo.getAreaCode();
            if (StrUtil.isBlank(areaCode)) {
                areaCode = "421100000000";
            }
            List<AreaInfo> areaInfos = areaInfoMapper.selectList(new LambdaQueryWrapper<AreaInfo>().eq(AreaInfo::getParentCode, areaCode));
            return Answer.ok(areaInfos);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getAreaChildInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> getAllAreaInfo() {
        try {
            List<AreaInfo> areaInfos = areaInfoMapper.selectList(null);
            List<AreaInfo> tree = new ArrayList<>();
            Map<String, AreaInfo> map = new HashMap<>();
            // 先将所有节点放入 map 中
            for (AreaInfo node : areaInfos) {
                map.put(node.getAreaCode(), node);
            }
            // 构建树形结构
            for (AreaInfo node : areaInfos) {
                String parentCode = node.getParentCode();
                if (parentCode == null || !map.containsKey(parentCode)) {
                    // 根节点
                    tree.add(node);
                } else {
                    // 非根节点，添加到父节点的 children 列表中
                    AreaInfo parent = map.get(parentCode);
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
            List<JSONObject> resList = new ArrayList<>();
            for (AreaInfo node : tree) {
                JSONObject json = convertToJsonByArea(node);
                resList.add(json);
            }
            return Answer.ok(resList);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getAllAreaInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> queryAreaInfoPage(cn.hutool.json.JSONObject reqJson) {
        try{
            Integer pageNum = reqJson.getInt("pageNum");
            Integer pageSize = reqJson.getInt("pageSize");
            IPage<AreaInfo> page = new Page<>(pageNum, pageSize);
            String areaName = reqJson.getStr("areaName");
            String areaCode = reqJson.getStr("areaCode");
            String parentCode = reqJson.getStr("parentCode");
            String parentName = reqJson.getStr("parentName");
            LambdaQueryWrapper<AreaInfo> areaInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotBlank(areaName)) {
                areaInfoLambdaQueryWrapper.like(AreaInfo::getAreaName, areaName);
            }
            if (StrUtil.isNotBlank(areaCode)) {
                areaInfoLambdaQueryWrapper.eq(AreaInfo::getAreaCode, areaCode);
            }
            if (StrUtil.isNotBlank(parentCode)) {
                areaInfoLambdaQueryWrapper.eq(AreaInfo::getParentCode, parentCode);
            }
            if (StrUtil.isNotBlank(parentName)) {
                areaInfoLambdaQueryWrapper.like(AreaInfo::getParentName, parentName);
            }
            areaInfoLambdaQueryWrapper.orderByAsc(AreaInfo::getId);
            IPage<AreaInfo> areaInfoIPage = areaInfoMapper.selectPage(page, areaInfoLambdaQueryWrapper);
            return Answer.ok(areaInfoIPage);
        }catch (Exception e){
            return LOG.error(Answer.build(), "请求queryAreaInfoPage失败！", e);
        }

    }

    private JSONObject convertToJsonByArea(AreaInfo node) {
        JSONObject json = new JSONObject();
        json.put("areaCode", node.getAreaCode());
        json.put("nameType", node.getAreaName());
        json.put("id", node.getId());
        List<AreaInfo> children = node.getChildren();
        if (children != null && !children.isEmpty()) {
            List<JSONObject> childrenJson = new ArrayList<>();
            for (AreaInfo child : children) {
                childrenJson.add(convertToJsonByArea(child));
            }
            json.put("childType", childrenJson);
        }
        return json;
    }
}
